package com.ygj.meeting.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.base.common.ConfigConstants;
import com.base.common.GlobaConstants;
import com.base.common.enums.MeetingStatus;
import com.base.common.json.JsonUtil;
import com.base.common.persistent.dao.EmployeeMapper;
import com.base.common.persistent.dao.MeetingAuthorizeMapper;
import com.base.common.persistent.dao.MeetingMapper;
import com.base.common.persistent.dao.MeetingSignRecordMapper;
import com.base.common.persistent.dao.SignPointMapper;
import com.base.common.persistent.model.Employee;
import com.base.common.persistent.model.Meeting;
import com.base.common.persistent.model.MeetingAuthorize;
import com.base.common.persistent.model.MeetingSignRecord;
import com.base.common.persistent.model.SignPoint;
import com.ygj.meeting.service.MeetingService;

@Service("meetingService")
public class MeetingServiceImpl implements MeetingService {

	@Resource
	private MeetingMapper meetingMapper;

	@Resource
	private SignPointMapper signPointMapper;

	@Resource
	private MeetingAuthorizeMapper meetingAuthorizeMapper;
	
	@Resource
	private MeetingSignRecordMapper meetingSignRecordMapper;
	
	@Resource
	private EmployeeMapper employeeMapper;

	@Transactional
	@Override
	public int addMeeting(Meeting meeting, String employeeIdListStr) {
		String code = getCode(GlobaConstants.MEETING_PREFIX);
		meeting.setCode(code);
		int result = meetingMapper.addMeeting(meeting);
		if (result == 1) {
			if (meeting != null && meeting.getIsNeedAuthorize() == 1
					&& employeeIdListStr != null
					&& !"".equals(employeeIdListStr)) {
				int meetingId = meetingMapper.queryMeetingByCode(code).getId();
				List<Integer> employeeIdList = JsonUtil.string2Obejct(
						employeeIdListStr, List.class);
				for (int employeeId : employeeIdList) {
					MeetingAuthorize meetingAuthorize = new MeetingAuthorize();
					meetingAuthorize.setEmployee(new Employee()
							.setId(employeeId));
					Meeting meeting2 = new Meeting();
					meeting2.setId(meetingId);
					meetingAuthorize.setMeeting(meeting2);
					meetingAuthorizeMapper
							.addMeetingAuthorize(meetingAuthorize);
				}
			}
			return 1;
		}
		return 0;
	}

	@Override
	public List<SignPoint> getSignPointByCompounds(int compoundsId) {
		return signPointMapper.querySignPointsByCompoundsId(compoundsId);
	}

	/**
	 * 生成会议编号
	 * 
	 * @param prefixCode
	 * @return
	 */
	@Transactional
	private String getCode(String prefixCode) {
		String lastedCode = meetingMapper.queryLastCode();
		DecimalFormat df = new DecimalFormat(ConfigConstants.TICKET_CODE_NUMS);
		String code = null;
		if (lastedCode != null && lastedCode.trim() != "") {
			code = df.format(Integer.parseInt(lastedCode.substring(1).trim()) + 1);
		} else {
			code = df.format(1);
		}
		code = prefixCode + code;
		return code;
	}

	@Override
	public List<Meeting> queryCouldJoinMeetingBySignPoint(int signPointId) {
		return meetingMapper.queryMeetingByStatusAndSignPointId(
				MeetingStatus.UNDERWAY.getValue(), signPointId);
	}

	@Transactional
	@Override
	public int sign(MeetingSignRecord meetingSignRecord) {
		if (meetingSignRecordMapper.queryMeetingRecordByMeetingAndEmployeeId(meetingSignRecord.getMeeting().getId(), meetingSignRecord.getEmployee().getId()).size() == 0) {
			List<Meeting> meetings = meetingMapper.queryMeetingByStatusAndId(MeetingStatus.UNDERWAY.getValue(), meetingSignRecord.getMeeting().getId());
			if(meetings.size() > 0){
				if (meetings.get(0).getIsNeedAuthorize() == 1) {
					if(meetingAuthorizeMapper.selectMeetingAuthorizeByMeetingIdAndEmployeeId(meetingSignRecord.getMeeting().getId(), meetingSignRecord.getEmployee().getId()).size() > 0){
						return meetingSignRecordMapper.addSignRecord(meetingSignRecord);
					} else {
						return 3;	// 无权限参加该会议
					}
				} else {
					return meetingSignRecordMapper.addSignRecord(meetingSignRecord);
				}
			} else {
				return 4;	// 会议已过期
			}
		}
		
		return 2;	// 已签到
	}

	@Override
	public int isHaveSign(int employeeId, int meetingId) {
		return meetingSignRecordMapper.queryMeetingRecordByMeetingAndEmployeeId(meetingId, employeeId).size();
	}

	@Override
	public List<Meeting> queryMeetingsByCondition(Map<String, Object> conditions, int page) {
		conditions.put("start", (page - 1) * Integer.valueOf(ConfigConstants.INFOS_LIST_NUM.trim()));
		conditions.put("end", page * Integer.valueOf(ConfigConstants.INFOS_LIST_NUM.trim()));
		return meetingMapper.queryMeetingsByCondition(conditions);
	}

	@Override
	public int queryMeetingCountsByCondition(Map<String, Object> conditions) {
		return meetingMapper.queryMeetingCountsByCondition(conditions);
	}

	@Override
	public List<MeetingSignRecord> queryMeetingRecordByMeetingId(int meetingId) {
		return meetingSignRecordMapper.queryMeetingRecordByMeetingId(meetingId);
	}

	@Override
	public Object queryJoinEmployee(int meetingId) {
		List<Map<String, Object>> result = new ArrayList<>();
		List<MeetingSignRecord> meetingSignRecords = meetingSignRecordMapper.queryMeetingRecordByMeetingId(meetingId);
		List<MeetingAuthorize> authorizes = meetingAuthorizeMapper.selectMeetingAuthorizeByMeetingIdAndEmployeeId(meetingId, 0);
		authorizes.stream().forEach(item -> {
			Map<String, Object> joinEmployee = new HashMap<>();
			List<MeetingSignRecord>  records = meetingSignRecords.stream().filter(record -> record.getEmployee().getId() == item.getEmployee().getId()).collect(Collectors.toList());
			Employee employee = employeeMapper.queryEmployeeById(item.getEmployee().getId());
			joinEmployee.put("id", employee.getId());
			joinEmployee.put("name", employee.getName());
			if(records.size() > 0) {
				joinEmployee.put("state", 1);
			} else {
				joinEmployee.put("state", 2);
			}
			result.add(joinEmployee);
		});
		
		return result;
	}

	@Transactional
	@Override
	public int updateJoinEmployee(int meetingId, String employeeIds) {
		
		Meeting meeting = meetingMapper.queryMeetingById(meetingId);
		if (meeting != null && meeting.getIsNeedAuthorize() == 1
				&& StringUtils.isNotBlank(employeeIds)) {
			List<Integer> employeeIdList = JsonUtil.string2Obejct(
					employeeIds, List.class);
			meetingAuthorizeMapper.deleteByMeetingId(meetingId);
			for (int employeeId : employeeIdList) {
				MeetingAuthorize meetingAuthorize = new MeetingAuthorize();
				meetingAuthorize.setEmployee(new Employee()
						.setId(employeeId));
				Meeting meeting2 = new Meeting();
				meeting2.setId(meetingId);
				meetingAuthorize.setMeeting(meeting2);
				meetingAuthorizeMapper
						.addMeetingAuthorize(meetingAuthorize);
			}
			return 1;
		}
		return 0;
	}

	@Override
	public int updateMeeting(int meetingId, String name, String description, Date startTime, Date endTime) {
		if(!(meetingMapper.queryMeetingById(meetingId).getStatus() == MeetingStatus.NOTBEGINNING.getValue())) {
			startTime = null;
			endTime = null;
		}
		return meetingMapper.updateMeetingById(meetingId, name, description, startTime, endTime);
	}
	
	
}
